package com.iespring.service.app.cart;

import com.iespring.bean.admin.goods.po.MallGoods;
import com.iespring.bean.admin.goods.po.MallGoodsProduct;
import com.iespring.bean.admin.promotion.po.MallCouponUser;
import com.iespring.bean.admin.user.entity.MallUser;
import com.iespring.bean.app.address.po.AddressPo;
import com.iespring.bean.app.cart.bo.*;
import com.iespring.bean.app.cart.po.MallCart;
import com.iespring.bean.app.cart.vo.*;
import com.iespring.bean.app.coupon.vo.WxCouponPageVo;
import com.iespring.bean.common.BaseRespVo;
import com.iespring.bean.common.CommonData;
import com.iespring.mapper.admin.*;
import com.iespring.mapper.app.WxCartMapper;
import com.iespring.service.app.coupon.WxCouponServiceImpl;
import com.iespring.util.UserInfoUtils;
import com.iespring.util.map.CartIdListUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author KeFei
 * @description: 小程序购物车模块
 * @date 2022/12/31 16:23
 */
@Service
public class WxCartServiceImpl implements WxCartService {

    @Resource
    WxCartMapper cartMapper;

    @Resource
    MallGoodsMapper goodsMapper;

    @Resource
    MallGoodsProductMapper productMapper;

    @Resource
    MallAddressMapper addressMapper;

    @Resource
    MallCouponMapper couponMapper;

    @Resource
    MallGrouponRulesMapper grouponRulesMapper;

    @Resource
    MallCouponUserMapper couponUserMapper;

    @Resource
    CartIdListUtils cartIdListUtils;

    @Resource
    WxCouponServiceImpl wxCouponService;

    /**
     * 获取购物车中的商品数量
     *
     * @return
     */
    @Override
    public int getCartGoodsNumber() {

        // 查询购物车中的商品数量
        List<CartIndexGoodsInfoVo> cartList = cartMapper.getCartGoodsList();

        return cartList.size();
    }

    /**
     * 添加购物车商品
     *
     * @param addCartGoodsBo
     */
    @Override
    public int addCartGoods(AddCartGoodsBo addCartGoodsBo) {

        // 创建cartIdList,用于存储checked=true的cartId数据
        List<Integer> cartIdList = new ArrayList<>();

        // 获取用户id
        MallUser user = UserInfoUtils.getUser();
        Integer userId = user.getId();
        // 获取加入到购物车的商品信息
        MallGoods goods = goodsMapper.getCartGoodsInfo(addCartGoodsBo.getGoodsId());
        // 获取商品详细规格信息
        MallGoodsProduct goodsProduct = productMapper.getCatGoodsProductInfo(addCartGoodsBo.getProductId());

        MallCart mallCart = new MallCart
                (null, userId, goods.getId(), goods.getGoodsSn(), goods.getName(), goodsProduct.getId(), goodsProduct.getPrice(), addCartGoodsBo.getNumber(), goodsProduct.getSpecifications(), true, goods.getPicUrl(), new Date(), new Date(), false);
        cartMapper.addCartGoods(mallCart);

        // 查询购物车中的商品数量
        List<CartIndexGoodsInfoVo> cartList = cartMapper.getCartGoodsList();
        int cartGoodsNumber = 0;
        for (CartIndexGoodsInfoVo cartGoods : cartList) {
            if (cartGoods.getChecked()) {
                cartGoodsNumber += cartGoods.getNumber();

                // 存储checked=true的cartId数据到cartIdList中
                cartIdList.add(cartGoods.getId());
            }
        }

        // 将checked=true的cartId数据都存到 session --> cartIdList 中
        // ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // HttpServletRequest request = sra.getRequest();
        // HttpSession session = request.getSession();
        // session.setAttribute("cartIdList", cartIdList);
        cartIdListUtils.setCartIdList(cartIdList);

        return cartGoodsNumber;
    }

    /**
     * 显示购物车主页
     *
     * @return
     */
    @Override
    public CartIndexVo cartIndex() {

        // 查找购物车中的商品信息
        List<CartIndexGoodsInfoVo> cartList = cartMapper.getCartGoodsList();

        // 统计购物车的信息
        // 购物车中已选择的商品的总金额
        BigDecimal checkedGoodsAmount = new BigDecimal(0);
        // 购物车中已选择的商品的总数量
        int checkedGoodsCount = 0;
        // 购物车中的商品总金额
        BigDecimal goodsAmount = new BigDecimal(0);
        // 购物车中的商品数量
        int goodsCount = cartList.size();
        for (CartIndexGoodsInfoVo cartGoods : cartList) {
            BigDecimal number = new BigDecimal(cartGoods.getNumber());
            if (cartGoods.getChecked()) {
                // 将number转成BigDecimal类型
                checkedGoodsAmount = checkedGoodsAmount.add(cartGoods.getPrice().multiply(number));
                checkedGoodsCount++;
            }
            goodsAmount = goodsAmount.add(cartGoods.getPrice().multiply(number));
        }
        // 封装购物车的信息
        CartIndexInfoVo cartTotal = new CartIndexInfoVo(checkedGoodsAmount, checkedGoodsCount, goodsAmount, goodsCount);

        CartIndexVo cartIndexVo = new CartIndexVo(cartList, cartTotal);
        return cartIndexVo;
    }

    /**
     * 修改购物车中某单个商品的数量
     *
     * @param updateCartGoodsNumberBo
     */
    @Override
    public void updateCartGoodsNumber(UpdateCartGoodsNumberBo updateCartGoodsNumberBo) {

        cartMapper.updateCartGoodsNumber(updateCartGoodsNumberBo);
    }

    /**
     * 改变购物车中商品的选择状态
     *
     * @param checkedStateBo
     * @return
     */
    @Override
    public CartIndexVo changeCheckedState(CheckedStateBo checkedStateBo) {

        // 创建cartIdList,用于存储checked=true的cartId数据
        List<Integer> cartIdList = new ArrayList<>();

        // 修改商品的选择状态
        int isChecked = checkedStateBo.getIsChecked();
        Integer[] productIds = checkedStateBo.getProductIds();
        cartMapper.changeCheckedState(isChecked, productIds);

        // 统计购物车的信息
        // 查找购物车中的商品信息
        List<CartIndexGoodsInfoVo> cartList = cartMapper.getCartGoodsList();
        // 购物车中已选择的商品的总金额
        BigDecimal checkedGoodsAmount = new BigDecimal(0);
        // 购物车中已选择的商品的总数量
        int checkedGoodsCount = 0;
        // 购物车中的商品总金额
        BigDecimal goodsAmount = new BigDecimal(0);
        // 购物车中的商品数量
        int goodsCount = cartList.size();
        for (CartIndexGoodsInfoVo cartGoods : cartList) {
            BigDecimal number = new BigDecimal(cartGoods.getNumber());
            if (cartGoods.getChecked()) {
                // 将number转成BigDecimal类型
                checkedGoodsAmount = checkedGoodsAmount.add(cartGoods.getPrice().multiply(number));
                checkedGoodsCount++;

                // 存储checked=true的cartId数据到cartIdList中
                cartIdList.add(cartGoods.getId());
            }
            goodsAmount = goodsAmount.add(cartGoods.getPrice().multiply(number));
        }

        // 将checked=true的cartId数据都存到 session --> cartIdList 中
        // ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // HttpServletRequest request = sra.getRequest();
        // HttpSession session = request.getSession();
        // session.setAttribute("cartIdList", cartIdList);
        // List<Integer> cartIdList1 = (List<Integer>) session.getAttribute("cartIdList");
        cartIdListUtils.setCartIdList(cartIdList);

        // 封装购物车的信息
        CartIndexInfoVo cartTotal = new CartIndexInfoVo(checkedGoodsAmount, checkedGoodsCount, goodsAmount, goodsCount);

        CartIndexVo cartIndexVo = new CartIndexVo(cartList, cartTotal);
        return cartIndexVo;
    }

    /**
     * 立即购买商品
     * <p>
     * 1.如果商品不在购物车中:
     * 点击立即购买后将其添加到购物车
     * 2.如果商品已在购物车中:
     * 点击立即购买时购买数量和购物车中的商品数量一致,则不做改变
     * 点击立即购买时购买数量和购物车中的商品数量不一致,则将立即购买时选择的数量覆盖购物车中的商品数量
     *
     * @param fastAddBo
     */
    @Override
    public int fastAdd(FastAddBo fastAddBo) {

        // 判断商品是否在购物车中
        Integer cartId = cartMapper.isExist(fastAddBo);
        if (cartId == null) {
            // 商品不存在 --> 将商品添加到购物车
            // 获取用户id
            MallUser user = UserInfoUtils.getUser();
            Integer userId = user.getId();
            // 获取加入到购物车的商品信息
            MallGoods goods = goodsMapper.getCartGoodsInfo(fastAddBo.getGoodsId());
            // 获取商品详细规格信息
            MallGoodsProduct goodsProduct = productMapper.getCatGoodsProductInfo(fastAddBo.getProductId());

            MallCart mallCart = new MallCart
                    (null, userId, goods.getId(), goods.getGoodsSn(), goods.getName(), goodsProduct.getId(), goodsProduct.getPrice(), fastAddBo.getNumber(), goodsProduct.getSpecifications(), true, goods.getPicUrl(), new Date(), new Date(), false);
            cartMapper.addCartGoods(mallCart);

            // 获取cartId
            Integer cartId1 = mallCart.getId();

            // 将checked=true的cartId数据都存到 session --> cartIdList 中
            // ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            // HttpServletRequest request = sra.getRequest();
            // HttpSession session = request.getSession();
            // List<Integer> cartIdList = (List<Integer>) session.getAttribute("cartIdList");
            // cartIdList.add(cartId1);
            // session.setAttribute("cartIdList", cartIdList);
            List<Integer> cartIdList = cartIdListUtils.getCartIdList();
            cartIdList.add(cartId1);
            cartIdListUtils.setCartIdList(cartIdList);

            return cartId1;
        } else {
            // 商品已在购物车中
            // 判断立即购买的商品数量和购物车中的商品数量是否相等
            // 立即购买商品的数量
            Short fastAddGoodsNumber = fastAddBo.getNumber();
            // 获取购物车中的商品数量
            Short cartGoodsNumber = cartMapper.getCartGoodsNumber(fastAddBo);
            if (fastAddGoodsNumber.equals(cartGoodsNumber)) {
                // 相等 --> 直接返回cartId
                return cartId;
            } else {
                // 不相等 --> 将立即购买时选择的数量覆盖购物车中的商品数量
                cartMapper.updateCartGoodsNumber(new UpdateCartGoodsNumberBo(cartId, fastAddBo.getGoodsId(), fastAddBo.getNumber(), fastAddBo.getProductId()));
                return cartId;
            }
        }
    }

    /**
     * 下单结账页面
     *
     * @param checkoutBo
     * @return
     */
    @Override
    public CheckoutVo checkout(CheckoutBo checkoutBo) {

        // 获取cartId
        Integer cartId = checkoutBo.getCartId();

        // 结账金额actualPrice
        BigDecimal actualPrice = new BigDecimal(0);

        // 获取用户的下单商品信息
        // 通过cartId判断操作:
        //      cartId=0   --> 购物车下单操作
        //      cartId!=0  --> 立即购买操作
        List<CartIndexGoodsInfoVo> checkedGoodsList = new ArrayList<>();
        if (checkoutBo.getCartId() == 0) {
            // 购物车下单操作
            // 获取购物车中已选择的商品的总金额
            List<CartIndexGoodsInfoVo> cartGoodsList = cartMapper.getCartGoodsList();
            for (CartIndexGoodsInfoVo cartGoods : cartGoodsList) {
                BigDecimal number = new BigDecimal(cartGoods.getNumber());
                if (cartGoods.getChecked()) {
                    actualPrice = actualPrice.add(cartGoods.getPrice().multiply(number));
                    // 将购物车中选择的商品添加到checkedGoodsList中
                    checkedGoodsList.add(cartGoods);
                }
            }
        } else {
            // 立即购买操作
            // 通过catId查询商品信息
            CartIndexGoodsInfoVo fastAddGoods = cartMapper.getCartGoodsListById(cartId);
            actualPrice = fastAddGoods.getPrice().multiply(new BigDecimal(fastAddGoods.getNumber()));
            checkedGoodsList.add(fastAddGoods);
        }

        // 其他信息
        // 获取用户选择的收货地址信息
        Integer addressId = checkoutBo.getAddressId();
        CheckedAddressVo checkedAddress = null;
        if (addressId != 0) {
            AddressPo address = addressMapper.getAddressByAddressId(addressId);
            checkedAddress = new CheckedAddressVo
                    (address.getId(), address.getName(), address.getUserId(), address.getProvince(), address.getCity(), address.getCounty(), address.getAddressDetail(), address.getAreaCode(), address.getTel(), address.getIsDefault(), address.getAddTime(), address.getUpdateTime(), address.getDeleted());
        }

        // 团购规则表id
        Integer grouponRulesId = checkoutBo.getGrouponRulesId();
        // 团购优惠金额
        BigDecimal grouponPrice = grouponRulesMapper.getGrouponPrice(grouponRulesId);

        // 优惠券用户使用表id
        Integer userCouponId = checkoutBo.getUserCouponId();
        // 查询可用优惠券数量
        int availableCouponLength = 0;
        BaseRespVo respVo = wxCouponService.selectList(cartId, 0);
        if (respVo.getErrno() != 0) {
            return null;
        }
        CommonData data = (CommonData) respVo.getData();
        // 有可用优惠券
        if (data != null) {
            availableCouponLength = data.getList().size();
        }
        // 无可用优惠券 --> availableCouponLength=0

        // 优惠券id
        Integer couponId = checkoutBo.getCouponId();
        BigDecimal couponPrice = new BigDecimal(0);
        // 判断:如果优惠券id=0,则不查询优惠券金额
        if (couponId != 0) {
            // 获取优惠券金额
            couponPrice = couponMapper.selectByPrimaryKey(couponId).getDiscount();
        }

        // 下单商品的总金额goodsTotalPrice
        BigDecimal goodsTotalPrice = actualPrice;
        // 计算运费价格
        BigDecimal freightPrice = new BigDecimal(0);
        BigDecimal freightRule = new BigDecimal(88);
        if (goodsTotalPrice.compareTo(freightRule) == -1) {
            // 订单金额不满88元,每单收取10元运费
            freightPrice = new BigDecimal(10);
        } else {
            // 订单金额满88元,免运费
        }

        // 订单最终价格 (下单商品的总金额 + 运费 - 优惠券金额)
        BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice).subtract(couponPrice);

        CheckoutVo checkoutVo = new CheckoutVo
                (actualPrice, addressId, availableCouponLength, cartId, checkedAddress, checkedGoodsList, couponId, couponPrice, freightPrice, goodsTotalPrice, grouponPrice, grouponRulesId, orderTotalPrice, userCouponId);

        return checkoutVo;
    }

    /**
     * 删除购物车中的商品
     *
     * @param deleteCartGoodsBo
     * @return
     */
    @Override
    public CartIndexVo deleteCartGoods(DeleteCartGoodsBo deleteCartGoodsBo) {

        // 创建cartIdList,用于存储checked=true的cartId数据
        List<Integer> cartIdList = new ArrayList<>();

        List<Integer> productIds = deleteCartGoodsBo.getProductIds();

        // 删除购物车中的商品
        cartMapper.deleteCartGoods(productIds);

        // 统计购物车的信息
        // 查找购物车中的商品信息
        List<CartIndexGoodsInfoVo> cartList = cartMapper.getCartGoodsList();
        // 购物车中已选择的商品的总金额
        BigDecimal checkedGoodsAmount = new BigDecimal(0);
        // 购物车中已选择的商品的总数量
        int checkedGoodsCount = 0;
        // 购物车中的商品总金额
        BigDecimal goodsAmount = new BigDecimal(0);
        // 购物车中的商品数量
        int goodsCount = cartList.size();
        for (CartIndexGoodsInfoVo cartGoods : cartList) {
            BigDecimal number = new BigDecimal(cartGoods.getNumber());
            if (cartGoods.getChecked()) {
                // 将number转成BigDecimal类型
                checkedGoodsAmount = checkedGoodsAmount.add(cartGoods.getPrice().multiply(number));
                checkedGoodsCount++;

                // 存储checked=true的cartId数据到cartIdList中
                cartIdList.add(cartGoods.getId());
            }
            goodsAmount = goodsAmount.add(cartGoods.getPrice().multiply(number));
        }

        // 将checked=true的cartId数据都存到 session --> cartIdList 中
        // ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // HttpServletRequest request = sra.getRequest();
        // HttpSession session = request.getSession();
        // session.setAttribute("cartIdList", cartIdList);
        cartIdListUtils.setCartIdList(cartIdList);

        // 封装购物车的信息
        CartIndexInfoVo cartTotal = new CartIndexInfoVo(checkedGoodsAmount, checkedGoodsCount, goodsAmount, goodsCount);

        CartIndexVo cartIndexVo = new CartIndexVo(cartList, cartTotal);
        return cartIndexVo;
    }

}
